﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using BLL;
using Models;

namespace Web
{
    public partial class admin_worksupdate : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            int wid = InitFromUrl("wid",0);
            if (wid == 0) {
                Response.Redirect("admin_works.aspx");
            }
            if (!IsPostBack)
            {
                BindData(wid);
            }
            else {
                BindWorksPicInfo(wid);
            }

            imgPicUrl.ImageUrl = hfPicUrl.Value;

            CKFinder.FileBrowser _FileBrowser = new CKFinder.FileBrowser();
            _FileBrowser.BasePath = "ckfinder/";
            _FileBrowser.SetupCKEditor(txbContent);
        }
        private int InitFromUrl(string url, int first)
        {
            int rtn = first;
            try
            {
                rtn = Int32.Parse(Request.QueryString[url].ToString());
            }
            catch { }
            return rtn;
        }
        private void BindData(int wid)
        {
            BindWorksCategory();
            BindNotice();
            //BindTop();
            BindWorksInfo(wid);
            BindWorksPicInfo(wid);
        }
        private void BindWorksCategory()
        {
            List<WorksCategoryInfo> list = WorksCategoryInfoLogic.GetAdminWorksCategory();//.GetAllWorksCategoryInfo();
            ddlCategory.DataSource = list;
            ddlCategory.DataTextField = "CategoryName";
            ddlCategory.DataValueField = "CategoryID";
            ddlCategory.DataBind();
        }
        private void BindWorksPicInfo(int wid)
        {
            List<WorksPicInfo> list = WorksPicInfoLogic.GetAllWorksPicInfo(wid);//.GetWorkAllPicInfo(wid);
            WorksPicRpt.DataSource = list;
            WorksPicRpt.DataBind();
        }
        private void BindWorksInfo(int wid)
        {
            WorksInfo work = WorksInfoLogic.GetWorksInfo(wid);
            txbTitle.Text = work.Title;
            txbCustomerName.Text = work.CustomerName;
            txbContent.Text = work.WorkContent;
            txbTeamWorkTime.Text = work.TeamWorkTime;
            ddlCategory.SelectedValue = work.CategoryID.ToString();
            hfPicUrl.Value = work.PicURL;
            txbWorksBrief.Text = work.WorksBrief;
        }
        //private void BindTop()
        //{
        //    List<int> list = new List<int>();
        //    for (int i = 0; i <= 100; i++)
        //    {
        //        list.Add(i);
        //    }
        //    ddlTop.DataSource = list;
        //    ddlTop.DataBind();
        //}
        private void BindNotice()
        {
            noticefail.Visible = false;
            noticesuccess.Visible = false;
        }
        protected void btnSubmit_OnClick(object sender, EventArgs e)
        {
            //if (Request.Form["picurl[]"] == null || Request.Form["piclevel[]"] == null)
            //{
            //    return;
            //}
            //string[] picurls = Request.Form["picurl[]"].Split(',');
            //string[] piclevels = Request.Form["piclevel[]"].Split(',');
            //string[] picnames = Request.Form["picname[]"].Split(',');
            ////string top = Request.Form["headshow"];
            //for (int i = 0; i < picurls.Count(); i++)
            //{
            //    WorksPicInfo pic = WorksPicInfoLogic.GetOnePicInfoFromURL(picurls[i]);
            //    if(pic.PicURL == picurls[i])
            //    {
            //        //pic的更新操作
            //    }
            //    else { 
            //        //pic的添加操作
            //        WorksPicInfoLogic.AddWorksPicInfo();
            //    }
            //}

            WorksInfo work = createWorksInfo();
            work.WorksID = InitFromUrl("wid",0);
            if (WorksInfoLogic.UpdateWorksInfo(work) != 1)
            {
                ChangeStatus(false);
                //noticefail.InnerText += "WorksInfo Updated Failed!";
                return;
            }

            //首先删除已经删除的照片
            if (!DeletePicInfo()) {
                ChangeStatus(false);
                //noticefail.InnerText += "Old Pic Deleted Failed!";
                return;
            }

            //处理需要添加的照片
            List<WorksPicInfo> piclist = createWorksPicList();
            foreach (var item in piclist)
            {
                item.WorksID = work.WorksID;
                WorksPicInfo pic = WorksPicInfoLogic.GetOnePicInfoFromURL(item.PicURL);
                if (pic.PicURL != item.PicURL)
                {
                    WorksPicInfoLogic.AddWorksPicInfo(item);
                }
                else {
                    item.PicID = pic.PicID;
                    WorksPicInfoLogic.UpdatePicInfo(item);
                }
            }

            ChangeStatus(true);
            BindWorksPicInfo(work.WorksID);
        }

        private void ChangeStatus(bool flag)
        {
            noticesuccess.Visible = flag ? true : false;
            noticefail.Visible = flag ? false : true;
            ScriptManager.RegisterStartupScript(this, this.GetType(), "initclosenotice", "AjaxChange();divupload();", true);
        }

        private List<WorksPicInfo> createWorksPicList()
        {
            List<WorksPicInfo> list = new List<WorksPicInfo>();
            if (Request.Form["picurl[]"] != null && Request.Form["piclevel[]"] != null)
            {
                string[] picurls = Request.Form["picurl[]"].Split(',');
                string[] piclevels = Request.Form["piclevel[]"].Split(',');
                string[] picnames = Request.Form["picname[]"].Split(',');
                //string top = Request.Form["headshow"];
                for (int i = 0; i < picurls.Count(); i++)
                {
                    WorksPicInfo wpi = new WorksPicInfo();
                    wpi.PicURL = picurls[i];
                    wpi.PicLevel = Int32.Parse(piclevels[i]);
                    wpi.PicName = picnames[i];
                    //if ((top == "" || top == null) && i == 0)
                    //{
                    //    wpi.TopFlag = 1;
                    //}
                    //else if (wpi.PicURL == top)
                    //{
                    //    wpi.TopFlag = 1;
                    //}
                    //else
                    //{
                    //    wpi.TopFlag = 0;
                    //}
                    list.Add(wpi);
                }
            }
            return list;
        }

        private WorksInfo createWorksInfo()
        {
            WorksInfo work = new WorksInfo();
            work.CategoryID = Int32.Parse(ddlCategory.SelectedValue);
            work.CustomerName = txbCustomerName.Text.Replace("'", "''");
            work.IsNWorks = 1;
            work.HotFlag = 0;
            //work.PublishTime = DateTime.Now;
            work.TeamWorkTime = txbTeamWorkTime.Text.Replace("'", "''");
            work.Title = txbTitle.Text.Replace("'", "''");
            work.TopFlag = 0;//
            work.WorkContent = txbContent.Text.Replace("'", "''");
            work.ClickCount = 0;
            work.PicURL = hfPicUrl.Value;
            work.WorksBrief = txbWorksBrief.Text.Replace("'","''");
            return work;
        }

        private bool DeletePicInfo()
        {
            if(Request.Form["delete[]"] == null)
            {
                return true;
            }
            int count = 0;
            string[] deletes = Request.Form["delete[]"].Split(',');
            List<WorksPicInfo> piclist = new List<WorksPicInfo>();
            foreach (var item in deletes)
            {
                int pid = Int32.Parse(item);
                count += WorksPicInfoLogic.DeletePicInfo(pid);
            }
            if (count == deletes.Count())
            {
                return true;
            }
            else {
                return false;
            }
        }
    }
}
